const mongoose = require("mongoose");
const request = require("request");
const addImage = require("../imageUtil/addImage");
const jmsPub = require("../../../jms/jmsPublisher.queue.js");
var Dish = mongoose.model("dish");
var Merchant = mongoose.model("merchant");

exports.addDish = function (req, res) {
    var dish = new Dish();
    var fileName = req.files.file.path;
    var imgName = fileName.substring(fileName.lastIndexOf("\\") + 1,fileName.length);
    var realPath = req.files.file.path;
    dish.dname = req.body.dname;
    dish.price = req.body.price;
    dish.status = 1;
    dish.createDate = new Date();
    dish.merchant = req.body.merchant;
    dish.img = imgName;
    addImage.addImage(imgName, realPath);
    dish.save(function (err) {
        if (!err) {
            res.json(dish);
        }else {
            res.json({error:"addDish"});
        }
    });
    Merchant.findOne({_id:req.body.merchant._id})
        .exec(function (err, merchant) {
            if (!err) {
                merchant.dish.push(dish);
                merchant.save(function (err) {});
            }
        });
}

//exports.loadDishByMerchant = function (req, res) {
//    Dish.find({merchant:req.session.merchant._id})
//        .exec(function (err, dishes) {
//            if (!err) {
//                req.json(dishes);
//            }
//            else {
//                res.json({error:"loadDishByMerchant"});
//            }
//        });
//}

exports.loadActiveDish = function (req, res) {
    Dish.find({merchant:req.session.merchant._id, $or:[{status:1}, {status:2}]})
        .exec(function (err, dishes) {
            if (!err) {
                console.log(dishes);
                res.json(dishes);
            }
            else {
                res.json({error:"loadActiveDish"});
            }
        });
}

exports.deleteDish = function (req, res) {
    Dish.findOne({_id:req.params.id})
        .exec(function (err, oldDish) {
            oldDish.status = 0;
            oldDish.save(function (err) {
                if (!err) {
                    res.json({msg : 'SUCCESS'});
                }
                else {
                    res.json({error:"deleteDish"});
                }
            });
        });
}

exports.recommendDish = function (req, res) {
    Dish.findOne({_id:req.params.id})
        .exec(function (err, dish) {
            if (!err) {
                jmsPub.publicRecommendedDish(dish.merchant, dish._id);
                dish.status = 2;
                dish.save(function (err) {
                    if (!err) {
                        res.json({msg : 'SUCCESS'});
                    }
                    else {
                        res.json({error:"recommendDish"});
                    }
                })
            }
            else {
                res.json({error:"recommendDish"});
            }
        });
}


